package com.xb.cloud.gateway.handler;

import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Type;
import java.util.Objects;

import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.JSONSerializer;
import com.alibaba.fastjson.serializer.ObjectSerializer;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.alibaba.fastjson.serializer.SerializeWriter;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.xb.cloud.gateway.client.Context;

@Component
public class ResponseRtnHandler implements Handler {

	public void execute(Context context) {
		try {
			HttpServletResponse response = context.getHttpResponse();
			if (context.getContentType() == null || context.getContentType().isEmpty()) {
				response.setContentType("application/json;charset=UTF-8");
				response.setCharacterEncoding("UTF-8");
			} else {
				response.setContentType(context.getContentType());
			}
			PrintWriter out = response.getWriter();
			if (context.getRtnText() != null && !context.getRtnText().equals("")) {
				out.println(context.getRtnText());
			} else {
				if (context.getRtnInfo() != null) {
					JSON.DEFFAULT_DATE_FORMAT = "yyyy-MM-dd HH:mm";
					
					final SerializeConfig resultJsonConfig = new SerializeConfig();
					resultJsonConfig.put(Long.class, new ObjectSerializer() {
						@Override
						public void write(JSONSerializer serializer, Object object, Object arg2, Type arg3)
								throws IOException {
							SerializeWriter out = serializer.getWriter();
							out.writeString(Objects.toString(object, null));
						}
					});

					String rtnText = JSON.toJSONString(context.getRtnInfo(), resultJsonConfig,
							SerializerFeature.WriteMapNullValue, SerializerFeature.WriteDateUseDateFormat,
							SerializerFeature.WriteNullListAsEmpty, SerializerFeature.WriteNullStringAsEmpty,
							SerializerFeature.WriteEnumUsingToString);
					out.println(rtnText);
				} else {
					out.println("");
				}
			}
			out.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
